import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios';
import { BASE_URL, TIMEOUT, ContentType } from './config';
import router from '@/router/index'
import { ElMessage } from 'element-plus'
import { useStore } from '@/store/index'

const authStore = useStore();
class HttpRequest {
  private axiosInstance: AxiosInstance;

  constructor(config: AxiosRequestConfig) {
    this.axiosInstance = axios.create(config);

    this.setupInterceptors();
  }

  private setupInterceptors() {
    this.axiosInstance.interceptors.request.use(
      (config) => {
        const token = authStore.token
        if (token) {
          config.headers.Authorization = token;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    this.axiosInstance.interceptors.response.use(
      (response: AxiosResponse)=> {
        const res = response.data;
        
        if(res.code == 6 && res.msg){
            //清除token
            authStore.clearToken();
            //重新登录
            router.push('/')
        }
        return response;
      },
      (error) => {
        ElMessage.error(error);
        return Promise.reject(error);
      }
    );
  }

  public get<T = any>(url: string, params?: any) {
    return this.axiosInstance.get<T>(url, { params });
  }

  public post<T = any>(url: string, data?: any) {
    return this.axiosInstance.post<T>(url, data);
  }
}

export const httpDefault = new HttpRequest({
  baseURL: BASE_URL,
  timeout: TIMEOUT,
  headers: {
    'Content-Type': ContentType.JSON
  }
});

export const httpFormData = new HttpRequest({
  baseURL: BASE_URL,
  timeout: TIMEOUT,
  headers: {
    'Content-Type': ContentType.FORM_DATA
  }
});